package com.example.statelayouthelper

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import cbfg.state.StateLayoutHelper
import com.example.statelayouthelper.databinding.FragmentDemo21Binding

/**
 * @Description: 参数 index 测试
 * @Author: TomHawk
 * @CreateDate: 2022/8/18 17:02
 *
 * 说明：添加布局到容器时如果没有指定 index，默认会添加到容器最后位置，
 *  有些情况下，添加到末尾位置会导致状态布局被添加到屏幕之外从而导致看不见，
 *  对于这种情况：
 *  1、可以通过指定 index 避免。
 *  2、如果容器是 LinearLayout 的话，设置 addToFirstIfLinearLayout 为 true 也可以避免。
 */
class Demo21Fragment : Fragment(R.layout.fragment_demo_21) {
    private var _binding: FragmentDemo21Binding? = null

    private val binding: FragmentDemo21Binding
        get() = _binding!!

    private lateinit var statusLayoutHelper: StateLayoutHelper

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentDemo21Binding.bind(view)
        binding.btnTest0.setOnClickListener {
            initStatusLayout(-1)
            statusLayoutHelper.showState(STATE_LOADING)
        }
        binding.btnTest1.setOnClickListener {
            initStatusLayout(0)
            statusLayoutHelper.showState(STATE_LOADING)
        }
        binding.btnTest2.setOnClickListener {
            initStatusLayout(0)
            statusLayoutHelper.showState(STATE_LOADING)
        }
    }

    private fun initStatusLayout(indexInContainer: Int) {
        if (this::statusLayoutHelper.isInitialized) {
            statusLayoutHelper.clearStates()
        }
        statusLayoutHelper = StateLayoutHelper.Builder(binding.root)
            .addState(STATE_LOADING, STATE_LOADING, true, indexInContainer)
            .setStateClickListener { helper, state, view ->
                if (state == STATE_LOADING && view.id == R.id.btnStateCancel) {
                    helper.hideState(STATE_LOADING)
                }
            }
            .build()
    }

    override fun onDestroy() {
        _binding = null
        super.onDestroy()
    }

    companion object {
        private const val STATE_LOADING = R.layout.layout_state_loading
    }
}